package com.jsh.erp.service.order;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.*;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.supplier.SupplierService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.BaseResponseInfo;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class OrderService {
    private Logger logger = LoggerFactory.getLogger(OrderService.class);

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderMapperEx orderMapperEx;
    @Resource
    private UserService userService;
    @Resource
    private LogService logService;
    @Resource
    private AccountHeadMapperEx accountHeadMapperEx;
    @Resource
    private DepotHeadMapperEx depotHeadMapperEx;
    @Resource
    private SupplierService supplierService;

    public Order getOrder(long id)throws Exception {
        Order result=null;
        try{
            result=orderMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }
    public Order getOrderByDdNum(String ddNum)throws Exception {
        Order result=null;
        try{
            result=orderMapperEx.selectByDdNum(ddNum);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }
    public List<OrderVoList> findByAll(String beizhu, String khxx, String beginTime,
                                    String endTime, String guige,String ddNum,String type,String satus) throws Exception{
        List<OrderVoList> list=null;
        try{
            list = orderMapperEx.findAllVO(khxx, beizhu, guige,ddNum, beginTime, endTime,type,satus);
//            if(list != null && list.size()>0){
//                for (Order order : list) {
//                    Supplier supplier = supplierService.getSupplier(Long.parseLong(order.getKhxx()));
//                    if(supplier != null) {
//                        order.setKhxx(supplier.getSupplier());
//                    }
//                }
//            }
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }
    public List<Order> getOrderListByIds(String ids)throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        List<Order> list = new ArrayList<>();
        try{
            OrderExample example = new OrderExample();
            example.createCriteria().andIdIn(idList);
            list = orderMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Order> getOrder()throws Exception {
        OrderExample example = new OrderExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Order> list=null;
        try{
            list= orderMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<OrderVoList> select(String khxx, String beizhu,String guige,String beignTime,String ddNum, String endTime,String type,String status,String jingshouren,int offset, int rows)throws Exception {
        List<OrderVoList> list=null;
        try{
            list= orderMapperEx.selectByConditionOrderVO(khxx, beizhu,guige,beignTime,endTime,ddNum,type,status,jingshouren,offset, rows);
            if(list != null && list.size()>0){
//                for (Order order : list) {
//                    Supplier supplier = supplierService.getSupplier(Long.parseLong(order.getKhxx()));
//                    if(supplier != null) {
//                        order.setKhxx(supplier.getSupplier());
//                    }else{
//                        order.setKhxx("信息异常");
//                    }
//                }
            }
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public Long countOrder(String khxx, String guige,String beizhu,String beignTime,String endTime,String ddNum,String type,String status,String jingshouren)throws Exception {
        Long result=null;
        try{
            result= orderMapperEx.countByOrder(khxx, beizhu,guige,beignTime,endTime,jingshouren,ddNum,type,status);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertOrder(String beanJson, HttpServletRequest request)throws Exception {
        Order order = JSONObject.parseObject(beanJson, Order.class);
        //默认未审批
        order.setStatus("0");
        if(StringUtil.isNotEmpty(order.getNumber()) && StringUtil.isNotEmpty(order.getDanjia())){
            Double number = Double.valueOf(order.getNumber());
            Double danjia = Double.valueOf(order.getDanjia());
            order.setZongjia(""+(number*danjia));
        }
        User curUser = (User)request.getSession().getAttribute("user");
        order.setJingshouren(String.valueOf(curUser.getId()));
        int result=0;
        try{
            result = orderMapper.insertSelective(order);
            logService.insertLog("经手人",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(order.getJingshouren()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
            public int updateOrder(String beanJson, Long id, HttpServletRequest request)throws Exception {
        Order order = JSONObject.parseObject(beanJson, Order.class);
        order.setId(id);
        Order idOrder = orderMapper.selectByPrimaryKey(id);
        order.setStatus(idOrder.getStatus());
        order.setCurrentGongxu(idOrder.getCurrentGongxu());
        order.setJingshouren(idOrder.getJingshouren());
        order.setChuhuoren(idOrder.getChuhuoren());
        if(StringUtil.isNotEmpty(order.getNumber()) && StringUtil.isNotEmpty(order.getDanjia())){
            Double number = Double.valueOf(order.getNumber());
            Double danjia = Double.valueOf(order.getDanjia());
            order.setZongjia(""+(number*danjia));
        }
        int result=0;
        try{
            result = orderMapper.updateByPrimaryKeySelective(order);
            logService.insertLog("经手人",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(order.getJingshouren()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateOrder(Order order,HttpServletRequest request)throws Exception {
        int result=0;
        try{
            result = orderMapper.updateByPrimaryKeySelective(order);
            logService.insertLog("经手人",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(order.getJingshouren()).toString(),request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteOrder(Long id, HttpServletRequest request)throws Exception {
        int result=0;
        try{
            result= orderMapper.deleteByPrimaryKey(id);
            logService.insertLog("经手人",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_DELETE).append(id).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateStatus(String ids, String status,String chuhuoren,HttpServletRequest request)throws Exception {
        int result=0;
        String idsArray[]=ids.split(",");
        String sjchrq = StringUtil.getSysDate("");
        try{
            result= orderMapperEx.batchChuhuoByIds(idsArray,status,chuhuoren,sjchrq);
            logService.insertLog("经手人",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_DELETE).append(ids).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteOrder(String ids, HttpServletRequest request) throws Exception{
        List<Long> idList = StringUtil.strToLongList(ids);
        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria().andIdIn(idList);
        int result=0;
        try{
            result= orderMapper.deleteByExample(orderExample);
            logService.insertLog("经手人", "批量删除,id集:" + ids, request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public BaseResponseInfo importExcel(List<Order> mList) throws Exception {
        logService.insertLog("订单",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_IMPORT).append(mList.size()).append(BusinessConstants.LOG_DATA_UNIT).toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        BaseResponseInfo info = new BaseResponseInfo();
        Map<String, Object> data = new HashMap<String, Object>();
        try {
            for(Order s: mList) {
                orderMapper.insertSelective(s);
            }
            info.code = 200;
            data.put("message", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            info.code = 500;
            data.put("message", e.getMessage());
        }
        info.data = data;
        return info;
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteByIds(String ids)throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
        List<Order> list = getOrderListByIds(ids);
        for(Order order: list){
            sb.append("[").append(order.getDdNum()).append("]");
        }
        logService.insertLog("经手人", sb.toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        User userInfo=userService.getCurrentUser();
        String [] idArray=ids.split(",");
        int result =0;
        try{
            result=orderMapperEx.batchDeleteOrderByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
    /**
     * create by: qiankunpingtai
     * website：https://qiankunpingtai.cn
     * description:
     *正常删除，要考虑数据完整性，进行完整性校验
     * create time: 2019/4/10 14:48
     * @Param: ids
     * @return int
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteByIdsNormal(String ids) throws Exception {
        /**
         * 校验
         * 1、财务主表	jsh_accounthead
         * 2、单据主表	jsh_depot_head
         * 是否有相关数据
         * */
        int deleteTotal=0;
        if(StringUtils.isEmpty(ids)){
            return deleteTotal;
        }
        String [] idArray=ids.split(",");
        /**
         * 校验财务主表	jsh_accounthead
         * */
        List<AccountHead> accountHeadList=null;
        try{
            accountHeadList = accountHeadMapperEx.getAccountHeadListByOrganIds(idArray);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        if(accountHeadList!=null&&accountHeadList.size()>0){
            logger.error("异常码[{}],异常提示[{}],参数,OrganIds[{}]",
                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,ExceptionConstants.DELETE_FORCE_CONFIRM_MSG,ids);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
                    ExceptionConstants.DELETE_FORCE_CONFIRM_MSG);
        }
        /**
         * 校验单据主表	jsh_depot_head
         * */
        List<DepotHead> depotHeadList=null;
        try{
            depotHeadList = depotHeadMapperEx.getDepotHeadListByOrganIds(idArray);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        if(depotHeadList!=null&&depotHeadList.size()>0){
            logger.error("异常码[{}],异常提示[{}],参数,OrganIds[{}]",
                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,ExceptionConstants.DELETE_FORCE_CONFIRM_MSG,ids);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
                    ExceptionConstants.DELETE_FORCE_CONFIRM_MSG);
        }
        /**
         * 校验通过执行删除操作
         * */
        deleteTotal= batchDeleteByIds(ids);
        return deleteTotal;

    }
    /**
     * 查询编号是否存在
     * @param id
     * @param name
     * @return
     * @throws Exception
     */
    public int checkIsNameExist(Long id, String name) throws Exception{
        OrderExample example = new OrderExample();
        example.createCriteria().andIdNotEqualTo(id).andDdNumEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Order> list =null;
        try{
            list = orderMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list==null?0:list.size();
    }

}
